<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold; font-size: 18px;">快</div>
          <div style="margin-left: 12px;">
            <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
          </div>
        </div>
      </div>

      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')"><i class="fas fa-chart-line"></i><span>数据总览</span></button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')"><i class="fas fa-box"></i><span>订单管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>

        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>
        

        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>

      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div style="background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
        <div></div>
        <div style="position: relative;">
          <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
          <input type="text" placeholder="搜索..." style="padding: 8px 12px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 240px; font-size: 14px;">
        </div>
      </div>

      <!-- Content -->
      <div style="padding: 32px;">
        <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 32px;">
          <div>
            <h1 style="font-size: 28px; font-weight: 700; color: #111827; margin-bottom: 8px;">系统日志</h1>
            <p style="color: #6b7280;">查看系统操作记录和异常日志</p>
          </div>
          <div style="display: flex; gap: 12px;">
            <button @click="showFilter = !showFilter" style="padding: 10px 20px; background: #f3f4f6; color: #374151; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 14px;"><i class="fas fa-filter"></i><span>筛选</span></button>
            <button @click="exportLogs" style="padding: 10px 20px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 14px;"><i class="fas fa-download"></i><span>导出日志</span></button>
          </div>
        </div>

        <!-- 筛选表单 -->
        <div v-if="showFilter" class="content-card" style="margin-bottom: 24px;">
          <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px;">
            <div>
              <label style="display: block; margin-bottom: 6px; font-size: 14px; color: #374151;">操作类型</label>
              <select v-model="filters.operation_type" style="width: 100%; padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 8px;">
                <option value="">全部</option>
                <option value="create">创建</option>
                <option value="update">更新</option>
                <option value="delete">删除</option>
                <option value="login">登录</option>
              </select>
            </div>
            <div>
              <label style="display: block; margin-bottom: 6px; font-size: 14px; color: #374151;">开始日期</label>
              <input type="date" v-model="filters.start_date" style="width: 100%; padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 8px;">
            </div>
            <div>
              <label style="display: block; margin-bottom: 6px; font-size: 14px; color: #374151;">结束日期</label>
              <input type="date" v-model="filters.end_date" style="width: 100%; padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 8px;">
            </div>
          </div>
          <div style="margin-top: 16px; display: flex; gap: 12px; justify-content: flex-end;">
            <button @click="resetFilters" style="padding: 8px 16px; background: #f3f4f6; color: #374151; border: none; border-radius: 8px; cursor: pointer;">重置</button>
            <button @click="applyFilters" style="padding: 8px 16px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer;">应用</button>
          </div>
        </div>

        <div class="content-card">
          <div v-if="loading" style="text-align: center; padding: 40px; color: #9ca3af;">加载中...</div>
          <div v-else-if="logs.length === 0" style="text-align: center; padding: 40px; color: #9ca3af;">暂无日志</div>
          <div v-else>
            <div 
              v-for="log in logs" 
              :key="log.id"
              :class="['log-item', getLogType(log.operation_type)]"
            >
              <div style="display:flex; justify-content: space-between;">
                <div><span :class="['status-badge', 'badge-' + getLogType(log.operation_type)]">{{ log.operation_type?.toUpperCase() || 'INFO' }}</span> {{ log.operation_details || '操作记录' }}</div>
                <div style="color:#6b7280;">{{ formatDate(log.created_at) }}</div>
              </div>
              <div style="color:#6b7280; font-size:13px; margin-top:6px;">
                操作人：{{ log.admin_name || log.admin_phone || '系统' }} | IP：{{ log.ip_address || '-' }} | {{ log.target_type ? `目标：${log.target_type}` : '' }}
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div v-if="totalPages > 1" style="margin-top: 24px; display: flex; justify-content: center; gap: 8px;">
            <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 8px; cursor: pointer;">上一页</button>
            <span style="padding: 8px 16px; color: #374151;">{{ currentPage }} / {{ totalPages }}</span>
            <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" style="padding: 8px 12px; border: 1px solid #e5e7eb; background: white; border-radius: 8px; cursor: pointer;">下一页</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AdminLogs',
  data() {
    return {
      logs: [],
      loading: false,
      showFilter: false,
      filters: {
        operation_type: '',
        start_date: '',
        end_date: ''
      },
      currentPage: 1,
      pageSize: 20,
      totalPages: 1
    }
  },
  methods: {
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    formatDate(dateStr) {
      if (!dateStr) return '-'
      try {
        return new Date(dateStr).toLocaleString('zh-CN')
      } catch {
        return dateStr
      }
    },
    getLogType(operationType) {
      if (!operationType) return 'info'
      const type = operationType.toLowerCase()
      if (type.includes('error') || type.includes('fail')) return 'error'
      if (type.includes('warning')) return 'warning'
      if (type.includes('success') || type === 'update' || type === 'create') return 'success'
      return 'info'
    },
    async loadLogs() {
      this.loading = true
      try {
        const params = new URLSearchParams({
          page: this.currentPage,
          pageSize: this.pageSize,
          ...this.filters
        })
        const res = await fetch(`/api/admin/logs?${params}`)
        const data = await res.json()
        if (data && data.success) {
          this.logs = data.data || []
          this.totalPages = Math.ceil((data.total || 0) / this.pageSize)
        }
      } catch (e) {
        console.error('加载日志失败', e)
      } finally {
        this.loading = false
      }
    },
    applyFilters() {
      this.currentPage = 1
      this.loadLogs()
      this.showFilter = false
    },
    resetFilters() {
      this.filters = {
        operation_type: '',
        start_date: '',
        end_date: ''
      }
      this.applyFilters()
    },
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page
        this.loadLogs()
      }
    },
    exportLogs() {
      const params = new URLSearchParams(this.filters)
      window.open(`/api/admin/logs?${params}&export=true`, '_blank')
    }
  },
  mounted() {
    this.loadLogs()
  }
}
</script>

<style scoped>
.sidebar { position: fixed; left: 0; top: 0; width: 240px; height: 100vh; background: #fff; border-right: 1px solid #e5e7eb; overflow-y: auto; }
.main-content { margin-left: 240px; min-height: 100vh; }
.nav-item { display: flex; align-items: center; padding: 12px 20px; color: #6b7280; text-decoration: none; transition: all 0.2s; cursor: pointer; width: 100%; background: transparent; border: 0; text-align: left; }
.nav-item:hover { background: #f3f4f6; color: #3b82f6; }
.nav-item.active { background: #eff6ff; color: #3b82f6; font-weight: 500; }
.nav-item i { width: 20px; margin-right: 12px; }
.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
.content-card { background: white; border-radius: 12px; padding: 24px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.log-item { border-left: 3px solid #e5e7eb; padding: 16px 20px; margin-bottom: 12px; background: #f9fafb; border-radius: 0 8px 8px 0; transition: all 0.2s; }
.log-item:hover { background: white; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
.log-item.info { border-left-color: #3b82f6; }
.log-item.success { border-left-color: #10b981; }
.log-item.warning { border-left-color: #f59e0b; }
.log-item.error { border-left-color: #ef4444; }
.status-badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.badge-info { background: #dbeafe; color: #1e40af; }
.badge-success { background: #d1fae5; color: #065f46; }
.badge-warning { background: #fef3c7; color: #92400e; }
.badge-error { background: #fee2e2; color: #991b1b; }
</style>
